package com.xiongjie.v5;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.security.*;

import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

public class Itext5Signaturel {

    public static String basePath="v5/src/main/resources/";

    public static void main(String[] args) throws Exception {
//        sign(new FileInputStream(basePath+"hello.pdf"), new FileOutputStream(basePath+"hello_signature.pdf"), new FileInputStream( "/Users/admin/myKey.jks"), "123456".toCharArray(), "理由", "位置", basePath + "签章图片.png");

        codeCreateSignaturePdf(basePath+"codeSignature.pdf");
    }

    /**
     * 在已经生成的pdf上添加电子签章，生成新的pdf并将其输出出来
     */
    public static void sign(InputStream src,OutputStream dest, InputStream p12Stream, char[] password, String reason, String location, String chapterPath) throws Exception {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(p12Stream, password);
        String alias = ks.aliases().nextElement();
        PrivateKey pk = (PrivateKey) ks.getKey(alias, password);
        Certificate[] chain = ks.getCertificateChain(alias);

        PdfReader reader = new PdfReader(src);
        PdfStamper stamper = PdfStamper.createSignature(reader, dest, '\0', null, false);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason(reason);
        appearance.setLocation(location);
        appearance.setVisibleSignature(new Rectangle(300, 600, 630, 500), 1, "sig1");

        Image image = Image.getInstance(chapterPath);
        appearance.setSignatureGraphic(image);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);

        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

        ExternalDigest digest = new BouncyCastleDigest();
        ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, null);
        MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);
    }

    public static void codeCreateSignaturePdf(String filename) throws Exception {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.add(new Paragraph("Hello World!"));

        PdfFormField field = PdfFormField.createSignature(writer);
        field.setFieldName("Mysig");
        field.setPage();
        field.setWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_INVERT);
        field.setFlags(PdfAnnotation.FLAGS_PRINT);
        writer.addAnnotation(field);

        PdfAppearance tp = PdfAppearance.createAppearance(writer, 72, 48);
        tp.setColorStroke(BaseColor.BLUE);
        tp.setColorFill(BaseColor.LIGHT_GRAY);
        tp.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
        tp.fillStroke();
        tp.setColorFill(BaseColor.BLUE);
        ColumnText.showTextAligned(tp, Element.ALIGN_CENTER, new Phrase("SIGN HERE"), 36, 24, 25);
        field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
        document.close();
    }
}
